package com.java2nb.novel.utils;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * Redisson分布式锁工具类
 */
@Component
public class RedissonLockUtils {
    @Autowired
    private RedissonClient redissonClient;
    // 存储已获取的锁
    private final Map<String, RLock> lockMap = new ConcurrentHashMap<>();

    /**
     * 获取分布式锁
     * @param lockKey 锁Key
     * @param waitTime 等待时间（ms）
     * @param leaseTime 持有时间（ms）
     * @return true=获取成功，false=获取失败
     */
    public boolean tryLock(String lockKey, long waitTime, long leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        lockMap.put(lockKey, lock); // 存储锁实例
        try {
            // 尝试获取锁，等待waitTime，持有leaseTime后自动释放
            return lock.tryLock(waitTime, leaseTime, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    /**
     * 释放分布式锁
     * @param lockKey 锁Key
     */
    public void unlock(String lockKey) {
        //RLock lock = redissonClient.getLock(lockKey);
        RLock lock = lockMap.get(lockKey);
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
            lockMap.remove(lockKey); // 清理锁实例
        }
    }
}